import tkinter
from PIL import Image, ImageTk
import tkmacosx
from tkinter.messagebox import *
import pymysql
import gui_index


def check_reg_db(usr, passwd, tpasswd):
    if passwd != tpasswd:
        showinfo("123", "两次输入密码不一致")
    else:
        db = pymysql.connect(host='180.102.129.53', user='root', passwd='520hhy', db='hhy', charset='utf8')
        cursor = db.cursor()
        sql = "select * from login where username ='{}'".format(usr)
        cursor.execute(sql)
        res = cursor.fetchall()
        if len(res) == 0:
            sql = """INSERT INTO login (username,password) VALUES("{}","{}")""".format(usr,passwd)
            cursor.execute(sql)
            db.commit()
            showinfo("showinfo", "注册成功，请重新登陆")
        else:
            # i[0]为账号，i[1]为密码，如果没查到 res是空的
            showinfo("", "该账号已经存在")


def resize(w_box, h_box, pil_image):
    # 参数是：要适应的窗口宽、高、Image.open后的图片
    # 处理自适应大小
    w, h = pil_image.size  # 获取图像的原始大小
    f1 = 1.0 * w_box / w
    f2 = 1.0 * h_box / h
    factor = min([f1, f2])
    width = int(w * factor)
    height = int(h * factor)
    return pil_image.resize((width, height), Image.ANTIALIAS)


def create_reg():
    log = tkinter.Tk()
    log.title("数据可视化平台注册")
    log.geometry('300x250')
    # can = tkinter.Canvas(log, height=200, width=200)
    img1 = Image.open(r'../non/1.png')
    img1 = resize(100, 100, img1)
    img2 = ImageTk.PhotoImage(img1)
    img_label = tkinter.Label(log, image=img2)
    img_label.grid(row=0, column=1, columnspan=2)
    username_str = tkinter.StringVar()
    username = tkinter.Entry(bg="white", fg="black", textvariable=username_str)
    password_str = tkinter.StringVar()
    password = tkinter.Entry(bg="white", fg="black", textvariable=password_str, show='*')
    tpassword_str = tkinter.StringVar()
    tpassword = tkinter.Entry(bg="white", fg="black", textvariable=tpassword_str, show='*')
    zhanghu = tkinter.Label(log, text="账号:")
    mima = tkinter.Label(log, text="密码:")
    qrmima = tkinter.Label(log, text="确认密码:")
    zhanghu.grid(row=1, column=0)
    username.grid(row=1, column=1)
    mima.grid(row=2, column=0)
    password.grid(row=2, column=1)
    qrmima.grid(row=3, column=0)
    tpassword.grid(row=3, column=1)
    # window可能会用到
    # login = tkinter.Button(log, text="登陆",bg="green",fg="black")
    button_text = tkinter.StringVar()
    button_text.set("注册")
    login = tkmacosx.Button(log, textvariable=button_text, bg="#339933", fg="white", width=180, height=40,
                            command=lambda: check_reg_db(username_str.get(), password_str.get(), tpassword_str.get()))
    login.grid(row=4, column=1, columnspan=3)
    log.mainloop()


if __name__ == '__main__':
    create_reg()
